<template>
  <div class="big-box">

    <div class="box-center">

      <!-- 头部导航 -->
      <div class="editor-top">
        <el-tooltip effect="light" content="退出编辑" placement="top">
          <div class="tooltip-trigger">
          <n-popconfirm @positive-click="returnEditor">
            <template #trigger>
              <img src="/src/assets/svg/return.svg" class="return-img">
            </template>
            您即将离开当前页面。请确认是否已保存内容。
          </n-popconfirm>
        </div>
        </el-tooltip>
        <el-tooltip effect="light" content="保存" placement="top">
          <img src="/src/assets/svg/save.svg" class="return-img" @click="save()">
        </el-tooltip>
        <span class="course--title">
        </span>
        <n-input v-model:value="title" type="text" size="large" placeholder="章节名" class="course-name" maxlength="30"
          show-count clearable />
          <!-- <n-button style="margin-left: 10px;"> 添加章节练习 </n-button> -->
      </div>

      <!-- 编辑器 -->
      <MdEditor v-model="MdText" ref="editorRef" :theme="MdEditorConfig.theme"
        :previewTheme="MdEditorConfig.previewTheme" :codeTheme="MdEditorConfig.codeTheme"
        :toolbars="MdEditorConfig.toolbars" :showToolbarName="MdEditorConfig.showToolbarName" @onUploadImg="onUploadImg"
        @onGetCatalog="onGetCatalog" @onBlur="onBlur" style="height: 90vh">
        <!-- 自定义工具栏 -->
        <template #defToolbars>
          <NormalToolbar title="插入视频" @Click="handleVideo('MyLove.mp4')">
            <template #trigger>
              <img src="../assets//svg//video.svg" style="padding: 4px; width: 16px; height: 16px" />
              <span style="font-size: 12px; white-space: nowrap">上传视频</span>
            </template>
          </NormalToolbar>
        </template>
      </MdEditor>
    </div>
  </div>
</template>

<!-- md-editor-v3 MdEditor富文本编辑器     hljs 代码高亮 -->
<script setup>
import { onMounted, reactive, ref, warn } from "vue";
//导入MdEditor富文本编辑器
import { MdEditor } from "md-editor-v3";
//导入MdEditor富文本编辑器自定义工具栏工具
import { NormalToolbar } from "md-editor-v3";
//导入MdEditor富文本编辑器样式
import "md-editor-v3/lib/style.css";
//导入代码高亮
import hljs from "highlight.js";
//导入代码高亮样式
import "highlight.js/styles/atom-one-dark.css";
import { upMdEditorImg, upMdEditorVideo } from "@/api/filesHttp";
import { openInfo } from "@/utils/openInfo";
import { useRouter } from "vue-router";
import adminHttp from "@/api/adminHttp";

const props = defineProps(['chapterId', 'courseId'])
//章节Id
const chapterId = props.chapterId
//所属课程ID
const courseId = props.courseId
//编辑器内容
const MdText = ref("");
const title = ref("")
const router = useRouter()
hljs.highlightAll(); //使用代码高亮

const editorRef = ref(null); //获取编辑器dom

onMounted(() => {
  //初始化章节数据
  getEditorDataById()
  editorRef.value?.on("catalog", console.log);
});

//获取该章节的数据
const getEditorDataById = () => {
  adminHttp.getEditorDataById(chapterId).then((res) => {
    if (res.code == 200) {
      console.log(res);
      MdText.value = res.data.content
      title.value = res.data.title
    }
  })
}

//插入视频
const handleVideo = () => {
  const inputEl = document.createElement("input"); //创建input元素
  inputEl.type = "file"; //数据类型
  inputEl.accept = "video/mp4, video/webm, video/ogg"; // 可以设置接受的文件类型，例如'*/*'表示任何类型
  inputEl.click(); //点击元素
  inputEl.addEventListener("change", function () {
    //用户选中文件的列表
    const files = inputEl.files;
    //console.log(files);
    //创建From对象装图片file
    const filesForm = new FormData();
    filesForm.append("file", files[0]);
    //上传视频文件
    upMdEditorVideo(filesForm).then((response) => {
      console.log(response);
      if (response.code == 200) {
        openInfo(response.data[0].msg, "success", "文件上传成功");
        //将视频插入到文档
        insertVideo(response.data[0]);
      } else {
        openInfo("文件上传失败");
      }
    });

  });
};

//配置视频文件上传基路径
const videoBaseUrl = "http://localhost:8085/file/video/";
//将视频元素插入编辑器
const insertVideo = (filename) => {
  editorRef.value.insert(() => {
    return {
      targetValue: `<P><video width="600" height="400" controls>
<source src="${videoBaseUrl}${filename}">
</video></P>`, //待插入内容
      select: false, //插入后是否自动选中内容
      deviationStart: 0, //插入后选中内容鼠标开始位置
      deviationEnd: 0, //插入后选中内容鼠标结束位置
    };
  });
};

//配置图片文件上传基路径
const imgBaseUrl = "http://localhost:8085/file/images/";
/* 图片文件上传事件 */
function onUploadImg(files, callback) {
  //创建From对象装图片file
  const filesForm = new FormData();
  console.log(files);

  files.forEach((file) => {
    filesForm.append("file", file);
  });

  //发送请求提交图片
  upMdEditorImg(filesForm).then((response) => {
    //触发回调函数把图片添加到 md 文档
    callback(
      response.data.map((item) => ({
        url: imgBaseUrl + item,
        alt: "",
        title: "",
      }))
    );
  });
}

/*list是标题列表 {text，level几级标题}不知道有什么用 */
const onGetCatalog = (list) => {
  //console.log(list);
  MdEditorConfig.catalogList = list;
};

/*输入框失去焦点时触发保存 */
const onBlur = (e) => {
  // save()
};

//创建编辑器
const MdEditorConfig = reactive({
  theme: "default", //编辑器主题 可选 default、dark
  previewTheme: "vuepress", //预览主题 可选 default、github、vuepress、mk-cute、smart-blue、cyanosis
  codeTheme: "tackoverflow", //代码主题 --感觉没效果
  catalogList: [], //目录
  //编辑器工具栏
  toolbars: ["prettier", "bold", "underline", "italic", "-", "title", "strikeThrough", "sub", "sup", "quote", "unorderedList", "orderedList", "task", "-", "codeRow", "code", "link", "image", "table", 0, "-", "revoke", "next", "=", "pageFullscreen", "fullscreen", "catalog",], //自定义工具栏
  showToolbarName: true,
});

//保存 上传服务器
const save = () => {
  const form = {
    courseId: courseId,
    chapterId: chapterId,
    title: title.value,
    content: MdText.value
  }
  adminHttp.saveMdEditor(form).then((res) => {
    if (res.code == 200) {
      openInfo("保存成功")
      console.log(res);
    }
  })
}


//返回上一级
const returnEditor = () => {

  router.back()
}


</script>

<style scoped>
.editor-top {
  height: 50px;
  display: flex;
  align-items: center;
  border: 1px rgb(236, 235, 228) solid;
  padding: 10px 5px 10px 5px;
  border-radius: 5px;
  margin-bottom: 2px;
}

.big-box {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.box-center {
  width: 95%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 阴影 */
}

.return-img {
  margin-left: 15px;
  cursor: pointer;
  transition: transform 0.4s ease;
}

.return-img:hover {
  transform: scale(1.3);
}

.course--title {
  margin-left: 20px;
  font-size: 20px;
  user-select: none;
}

.course-name {
  width: 400px;
}
</style>